package com.cloudcc.mobile.view.main.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.MenuToggleEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.db.ApprovalDB;
import com.cloudcc.mobile.db.ChatMessageDB;
import com.cloudcc.mobile.db.DraftBoxDB;
import com.cloudcc.mobile.db.EventDB;
import com.cloudcc.mobile.db.MessageDB;
import com.cloudcc.mobile.db.TaskDB;
import com.cloudcc.mobile.entity.Message;
import com.cloudcc.mobile.entity.chat.DraftBox;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.util.NotificationUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.view.activity.AboutMeActivty;
import com.cloudcc.mobile.view.activity.DraftBoxActivity;
import com.cloudcc.mobile.view.activity.MessageActivity;
import com.cloudcc.mobile.view.activity.TaskManagementActivty;
import com.cloudcc.mobile.view.activity.WebViewActivity;
import com.cloudcc.mobile.view.dynamic.AboutMeListActivty;
import com.cloudcc.mobile.view.im.ConversationListActivity;
import com.cloudcc.mobile.weight.ElasticScrollView;
import com.cloudcc.mobile.weight.ElasticScrollView.OnRefreshListener;
import com.easemob.chat.EMChatManager;
import com.lidroid.xutils.exception.DbException;

/**
 * 消息界面
 * 
 * @author seven
 * 
 */
public class MainMessageFragment extends Fragment {
	private LinearLayout at, event, task, daishenpi, systemmes, zan,
			caogaoxiang, pinglun, guanzhu, huanxin;
	private Context context;
	private TextView attime, atnum, attext, eventtime, eventnum, eventtext,
			messagetext, caogaotext, daishenpitext, tasktext, tasktime,
			tasknum, daishenpitime, daishenpinum, caogaotime, caogaonum,
			timetext, messagenum, imnum, imtimetext, imtext;
	private MessageDB db;
	private ChatMessageReceiver receiver;
	private ImageView menubtn;
	private MessageDB db1;
	private DraftBoxDB db2;
	private TaskDB db3;
	private ApprovalDB db4;
	private ElasticScrollView message_layout;
	private EventDB db5;
	private ChatMessageDB db6;
	//private HuanxinDB db7;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.chat_message, null);
		try {
			context = getActivity();
			setupView(view);
			setMessageNum();
			addListener();
		} catch (Exception e) {
			Tools.handle(e);
		}
		return view;
	}

	private void setMessageNum() throws DbException {
		// 设置消息数量
		long messnum = db.getNewMessageNum();
		long draftnum = db2.getNewDraftBoxNum();
		long taskNum = db3.getNewTaskNum();
		long approvalnum = db4.getNewApprovalNum();
		long eventNum = db5.getNewEventNum();
		long atNum = db6.getNewChatMessageNum();
		AppContext.dspnum = (int) approvalnum;
		AppContext.rwnum = (int) taskNum;
		AppContext.mesnum = (int) messnum;
		AppContext.eventnum = (int) eventNum;
		AppContext.atnum = (int) atNum;

		// 设置消息的数量显示
		if (messnum > 0) {
			messagenum.setVisibility(View.VISIBLE);
			if (messnum > 99) {
				messagenum.setText("99");
			} else {
				messagenum.setText("" + messnum);
			}
		} else {
			messagenum.setVisibility(View.INVISIBLE);
		}
		Message mes = db.getLastMessage();
		if (mes != null) {
			timetext.setVisibility(View.VISIBLE);
			messagetext.setVisibility(View.VISIBLE);
			timetext.setText(mes.getTime());
			messagetext.setText(mes.getContext());
		} else {
			timetext.setVisibility(View.INVISIBLE);
			messagetext.setText("暂无消息");
		}

		// 设置草稿箱的数量显示
		if (draftnum > 0) {
			caogaonum.setVisibility(View.VISIBLE);
			if (draftnum > 99) {
				caogaonum.setText("99");
			} else {
				caogaonum.setText("" + draftnum);
			}
		} else {
			caogaonum.setVisibility(View.INVISIBLE);
		}
		DraftBox box = db2.getLastDraftBox();
		if (box != null) {
			caogaotime.setVisibility(View.VISIBLE);
			caogaotext.setVisibility(View.VISIBLE);
			caogaotime.setText(box.getTime());
			String a = box.getType();
			if (a.equals("1")) {
				caogaotext.setText("签到");
			} else if (a.equals("2")) {
				caogaotext.setText("微贴");
			} else if (a.equals("3")) {
				caogaotext.setText("回复");
			}
		} else {
			caogaotime.setVisibility(View.INVISIBLE);
			caogaotext.setText("暂无内容");
		}
		/**
		 * 待审批数量显示
		 */
		if (approvalnum > 0) {
			daishenpinum.setVisibility(View.VISIBLE);
			daishenpitime.setVisibility(View.VISIBLE);
			daishenpi.setVisibility(View.VISIBLE);
			if (approvalnum > 99) {
				daishenpinum.setText("99");
			} else {
				daishenpinum.setText("" + approvalnum);
			}
			daishenpitime.setText(Tools.getTime(System.currentTimeMillis()));
			daishenpitext.setText("亲，您有" + approvalnum + "个待审批需要处理。");
		} else {
			daishenpitime.setVisibility(View.INVISIBLE);
			daishenpinum.setVisibility(View.INVISIBLE);
			daishenpitext.setText("审批事项列表");
		}

		/**
		 * 任务的数量显示
		 */
		if (taskNum > 0) {
			tasknum.setVisibility(View.VISIBLE);
			tasktime.setVisibility(View.VISIBLE);
			task.setVisibility(View.VISIBLE);
			if (taskNum > 99) {
				tasknum.setText("99");
			} else {
				tasknum.setText("" + taskNum);
			}
			tasktime.setText(Tools.getTime(System.currentTimeMillis()));
			tasktext.setText("亲，您有" + taskNum + "个任务需要处理。");
		} else {
			tasktime.setVisibility(View.INVISIBLE);
			tasknum.setVisibility(View.INVISIBLE);
			tasktext.setText("自己的、上级交派的任务,也可给同事交派任务。");
		}

		/**
		 * 事件的数量显示
		 */
		if (eventNum > 0) {
			eventnum.setVisibility(View.VISIBLE);
			eventtime.setVisibility(View.VISIBLE);
			event.setVisibility(View.VISIBLE);
			if (eventNum > 99) {
				eventnum.setText("99");
			} else {
				eventnum.setText("" + eventNum);
			}
			eventtime.setText(Tools.getTime(System.currentTimeMillis()));
			eventtext.setText("亲，您有" + eventNum + "个日程事件需要处理。");
		} else {
			eventtime.setVisibility(View.INVISIBLE);
			eventnum.setVisibility(View.INVISIBLE);
			eventtext.setText("日常活动计划，与客户互动的日志记录。");
		}
		/**
		 * chat回复，留言，等
		 */
		if (atNum > 0) {
			atnum.setVisibility(View.VISIBLE);
			attime.setVisibility(View.VISIBLE);
			at.setVisibility(View.VISIBLE);
			if (atNum > 99) {
				atnum.setText("99");
			} else {
				atnum.setText("" + atNum);
			}
			attime.setText(Tools.getTime(System.currentTimeMillis()));
			String text = db6.getLastChatMessage().getContext();
			attext.setText(text);
		} else {
			atnum.setVisibility(View.INVISIBLE);
			attext.setText("亲，您还没有chat信息。");
		}
		message_layout.onRefreshComplete();
	}

	/**
	 * 做监听
	 */
	private void addListener() {
		menubtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EventEngine.post(new MenuToggleEvent(false, false));
			}
		});
		huanxin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(context, ConversationListActivity.class);
				startActivity(i);
			}
		});
		/**
		 * chat消息
		 */
		at.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					/**
					 * 处理代码
					 */
					// db6.deleteChatMessageAll();
					// NotificationUtils.clearNotification(context, 2004);
					Intent messageNum = new Intent(AppContext.MESSAGE_CHAT_NUM);
					context.sendBroadcast(messageNum);
					Intent intent;
					if (db6.getNewChatMessageNum() == 0) {
						intent = new Intent(context, AboutMeActivty.class);
					} else {
						intent = new Intent(context, AboutMeListActivty.class);
					}
					startActivity(intent);
				} catch (DbException e) {
					Tools.handle(e);
				}
			}
		});
		/**
		 * 事件监听
		 */
		event.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				 try {
				 db5.deleteEventAll();
				 Intent intent=new Intent(context,WebViewActivity.class);
				 intent.putExtra("MyPushMessageReceiver", "event");
				 startActivity(intent);
				 } catch (DbException e) {
				 Tools.handle(e);
				 }
				// TODO 测试环信

			}
		});

		/**
		 * 消息
		 */
		message_layout.setonRefreshListener(new OnRefreshListener() {
			@Override
			public void onRefresh() {
				try {
					setMessageNum();
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		});
		/**
		 * 待审批
		 */
		daishenpi.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					db4.deleteApprovalAll();
					/*Intent intent2 = new Intent(context, WebViewActivity.class);
					intent2.putExtra("MyPushMessageReceiver", "approval");*/
					Intent intent=new Intent(AppContext.DAISHENPI_NUM);
					getActivity().sendBroadcast(intent);
					Intent intent2 = new Intent(context, TaskManagementActivty.class);
					startActivity(intent2);
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		});
		/**
		 * 任务
		 */
		task.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					db3.deleteTaskAll();
					Intent intent2 = new Intent(context, WebViewActivity.class);
					intent2.putExtra("MyPushMessageReceiver", "task");
					startActivity(intent2);
				} catch (DbException e) {
					e.printStackTrace();
				}
			}
		});

		/**
		 * 草稿箱
		 */
		caogaoxiang.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// try {
				// db2.clearDraftBoxNum();
				// } catch (DbException e) {
				// e.printStackTrace();
				// }
				Intent intent = new Intent(context, DraftBoxActivity.class);
				startActivity(intent);
			}
		});
		/**
		 * 系统消息
		 */
		systemmes.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				try {
					if (db.isExit()) {
						db.clearMessageNum();
					}
				} catch (DbException e) {
					Tools.handle(e);
				}
				NotificationUtils.clearNotification(context, 2000);
				Intent messageNum = new Intent(AppContext.MESSAGE_SYSTEM_NUM);
				context.sendBroadcast(messageNum);
				Intent intent = new Intent(context, MessageActivity.class);
				startActivity(intent);
			}
		});
	}

	/**
	 * 获取控件
	 * 
	 * @param view
	 */
	private void setupView(View view) {
		UserModel user = UserManager.getManager().getUser();
		db = new MessageDB(context, user.userId + "message");
		db2 = new DraftBoxDB(context, user.userId + "box.db");
		db3 = new TaskDB(context, user.userId + "chat");
		db4 = new ApprovalDB(context, user.userId + "chat");
		db5 = new EventDB(context, user.userId + "chat");
		db6 = new ChatMessageDB(context,
				UserManager.getManager().getUser().userId + "chat");

		//db7 = new HuanxinDB(context, user.userId + "chat");
		message_layout = (ElasticScrollView) view
				.findViewById(R.id.message_menu_chat);
		View views = LayoutInflater.from(context).inflate(
				R.layout.menu_message_item, null);
		message_layout.addChild(views, 1);
		message_layout.requestFocus();
		caogaoxiang = (LinearLayout) views.findViewById(R.id.caogaoxiang_chat);// 草稿箱
		systemmes = (LinearLayout) views.findViewById(R.id.systemmes_chat);// 系统消息
		daishenpi = (LinearLayout) views.findViewById(R.id.daishenpi_chat);// 待审批
		task = (LinearLayout) views.findViewById(R.id.task_chat);// 任务
		event = (LinearLayout) views.findViewById(R.id.event_chat);// 事件
		at = (LinearLayout) views.findViewById(R.id.at_chat);// @我的，回复我的
		
		//环信
		huanxin = (LinearLayout) views.findViewById(R.id.huanxin_chat);// 环信
		imnum = (TextView) views.findViewById(R.id.im_num);
		imtext = (TextView) views.findViewById(R.id.im_text);
		imtimetext = (TextView) views.findViewById(R.id.im_timetext);

		messagenum = (TextView) views.findViewById(R.id.systemmessnum);
		timetext = (TextView) views.findViewById(R.id.timetext);
		messagetext = (TextView) views.findViewById(R.id.message_text);

		caogaonum = (TextView) views.findViewById(R.id.caogaonum);
		caogaotime = (TextView) views.findViewById(R.id.caogao_timetext);
		caogaotext = (TextView) views.findViewById(R.id.caogao_text);

		daishenpinum = (TextView) views.findViewById(R.id.daishenpi_num);
		daishenpitime = (TextView) views.findViewById(R.id.daishenpi_timetext);
		daishenpitext = (TextView) views.findViewById(R.id.daishenpi_text);

		tasknum = (TextView) views.findViewById(R.id.task_num);
		tasktime = (TextView) views.findViewById(R.id.task_timetext);
		tasktext = (TextView) views.findViewById(R.id.task_text);

		eventtext = (TextView) views.findViewById(R.id.event_text);
		eventnum = (TextView) views.findViewById(R.id.event_num);
		eventtime = (TextView) views.findViewById(R.id.event_timetext);

		attext = (TextView) views.findViewById(R.id.at_text);
		atnum = (TextView) views.findViewById(R.id.at_num);
		attime = (TextView) views.findViewById(R.id.at_timetext);
		menubtn = (ImageView) view.findViewById(R.id.chatmes_menubtn);

		receiver = new ChatMessageReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppContext.MESSAGE_SYSTEM);
		filter.addAction(AppContext.MESSAGE_DAISHENPI);
		filter.addAction(AppContext.MESSAGE_DAIBANRENWU);
		filter.addAction(AppContext.MESSAGE_RICHENG_EVENT);
		filter.addAction(AppContext.MESSAGE_CHATMESSAGE);
		filter.addAction(AppContext.MESSAGE_SYSTEM_NUM);
		filter.addAction(AppContext.DAISHENPI_NUM);
		filter.addAction(AppContext.TASK_NUM);
		filter.addAction(AppContext.CAOGAO_NUM);
		filter.addAction(AppContext.EVENT_NUM);
		filter.addAction(AppContext.MESSAGE_CHAT_NUM);
		context.registerReceiver(receiver, filter);

	}

	@Override
	public void onDestroy() {
		try {
			context.unregisterReceiver(receiver);
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.onDestroy();
	}

	/**
	 * 广播接收器
	 * 
	 * @author Administrator
	 * 
	 */
	class ChatMessageReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(AppContext.MESSAGE_SYSTEM)
					|| action.equals(AppContext.MESSAGE_DAISHENPI)
					|| action.equals(AppContext.MESSAGE_DAIBANRENWU)
					|| action.equals(AppContext.MESSAGE_RICHENG_EVENT)
					|| action.equals(AppContext.MESSAGE_CHATMESSAGE)) {
				try {
					Tools.showInfo(context, "收到消息了撒");
					setMessageNum();
				} catch (DbException e) {
					e.printStackTrace();
				}
			} else if (action.equals(AppContext.MESSAGE_SYSTEM_NUM)
					|| action.equals(AppContext.DAISHENPI_NUM)
					|| action.equals(AppContext.TASK_NUM)
					|| action.equals(AppContext.CAOGAO_NUM)
					|| action.equals(AppContext.MESSAGE_CHAT_NUM)
					|| action.equals(AppContext.EVENT_NUM)) {
				try {
					setMessageNum();
				} catch (DbException e) {
					Tools.handle(e);
				}
			}
		}
	}



	public void Imset() {
		int unreadCount = getUnreadMsgCountTotal();
		if (unreadCount>0) {
			imnum.setVisibility(View.VISIBLE);
			imtimetext.setVisibility(View.VISIBLE);
			if (unreadCount > 99) {
				imnum.setText("99");
			} else {
				imnum.setText(String.valueOf(unreadCount));
			}
			imtext.setText("您有未读的消息...");
		}else{
			imnum.setVisibility(View.INVISIBLE);
			imtimetext.setVisibility(View.INVISIBLE);
			imtext.setText("暂无未读的消息...");
		}

	}

	/**
	 * 获取未读消息数
	 * 
	 * @return
	 */
	public int getUnreadMsgCountTotal() {
		int unreadMsgCountTotal = 0;
		unreadMsgCountTotal = EMChatManager.getInstance().getUnreadMsgsCount();
		return unreadMsgCountTotal;
	}

	@Override
	public void onResume() {
		super.onResume();
		Imset();
		try {
			setMessageNum();
		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
